package leetcode.string;

/**
 * @Description: https://leetcode.cn/problems/multiply-strings/description/
 * @Author Ammar
 * @Create 2023/8/5 10:17
 */
public class _43_字符串相乘 {
    public static void main(String[] args) {
        new _43_字符串相乘().multiply("123", "456");
    }

    public String multiply(String num1, String num2) {

        if (num1.equals("0") || num2.equals("0")) return "0";

        char[] cs1 = num1.toCharArray();
        char[] cs2 = num2.toCharArray();
        int[] nums = new int[cs1.length + cs2.length];

        for (int i = cs1.length - 1; i >= 0; i--) {
            int n1 = cs1[i] - '0';
            for (int j = cs2.length - 1; j >= 0; j--) {
                int n2 = cs2[j] - '0';
                int sum = nums[i + j + 1] + n1 * n2;
                nums[i + j + 1] = sum % 10;
                nums[i + j] += sum / 10;
            }
        }
        StringBuilder sb = new StringBuilder();
        boolean flag = true;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0 && flag) continue;
            if (nums[i] != 0 && flag) flag = false;
            sb.append(nums[i]);
        }
        return sb.toString();
    }
}
